package com.diyizu.youdianda.controller;

import com.diyizu.youdianda.common.FileInfo;
import com.diyizu.youdianda.common.R;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("common")
public class CommonController {
    @Value("${ydd.bpath}")
    private String bpath;
    @Value("${ydd.fpath}")
    private String fpath;

    @PostMapping("upload")
    public R upload(String type, MultipartFile file) {
        try {
            String fileName = Long.toString(System.currentTimeMillis());
            String endName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            String targetName = fileName + endName;
            File targetDir = new File(bpath);
            if (!targetDir.exists()) {
                targetDir.mkdirs();
            }
            File targetFile = new File(bpath, targetName);
            if (targetFile.exists()){
                targetFile.delete();
            }
            file.transferTo(targetFile);

            File file1 = new File(fpath, targetName);
            FileUtils.copyFile(targetFile,file1);

            FileInfo fileInfo = new FileInfo();
            fileInfo.setSavePath("upload/images/" + targetName);
            fileInfo.setName(file.getOriginalFilename());
            fileInfo.setMime("images/" + endName.replaceAll("\\.", ""));
            fileInfo.setSize(targetFile.length());
            return R.success(fileInfo);
        } catch (IOException e) {
            e.printStackTrace();
            return R.error("上传失败"+e.getMessage());
        }
    }
}
